// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.asm.tree;

import java.io.IOException;
import java.io.PrintWriter;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.util.TraceClassVisitor;

import com.dustedpixels.asm.ClassDebugInfoRemover;


/**
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public final class TreeUtils {
  public static MethodNode getMethod(ClassNode clazz, String name, String desc) {
    for (Object methodObject : clazz.methods) {
      MethodNode method = (MethodNode) methodObject;
      if (method.name.equals(name) && method.desc.equals(desc)) {
        return method;
      }
    }
    return null;
  }
  
  public static FieldNode getField(ClassNode clazz, String name) {
    for (Object fieldObject : clazz.fields) {
      FieldNode field = (FieldNode) fieldObject;
      if (field.name.equals(name)) {
        return field;
      }
    }
    return null;
  }
  
  public static void printTrace(ClassNode clazz) {
    clazz.accept(new TraceClassVisitor(new PrintWriter(System.out)));
  }
  
  public static void printTrace(MethodNode method) {
    ClassVisitor classVisitor = new TraceClassVisitor(new PrintWriter(System.out));
    MethodVisitor methodVisitor = classVisitor.visitMethod(
        method.access,
        method.name, 
        method.desc, 
        method.signature,
        (String[]) method.exceptions.toArray(new String[0]));
    method.accept(methodVisitor);
    classVisitor.visitEnd();
  }
  
  public static ClassNode load(String className) throws IOException {
    ClassNode clazz = new ClassNode();
    ClassReader classReader = new ClassReader(className.replace('.', '.'));
    classReader.accept(new ClassDebugInfoRemover(clazz), 0);
    return clazz;
  }
}
